<?php

/**
 * @desc ajax admin page
 * @version $Id: 20120122
 * @author n0aX
 * @package Administration
 */

$admin_request = $tk->page->_pv['admin_request'];
$admin_page = $tk->page->_pv['admin_page'];

foreach ( $_POST as $key => $value )
{
    $_POST[$key] = str_replace("\n", '', $_POST[$key]);
    $_POST[$key] = str_replace("\r\n", '', $_POST[$key]);
    $_POST[$key] = preg_replace('%^<br />$%', '', $_POST[$key]);
    ${$key} = $_POST[$key];
    
    if (in_array($settings['form_fields'][$key]['type'], array(
            'radio', 
            'checkbox'
    )))
    {
        ${$key} = isset(${$key}) ? ${$key} : (isset($settings['form_fields'][$key]['default']) ? $settings['form_fields'][$key]['default'] : 0);
    }
}

$tk->page->request = 'json';

/**
 * @method edit-
 */

if (preg_match('%^edit-.+$%i', $admin_request))
{
    $id = (int) $_GET['id'];
    
    if (! $id)
    {
        $error = 'no_record';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
        return;
    }
    
    $where_condition = "id = '$id'";
    
    $sql = "SELECT SQL_CACHE $item_override $item_fields from $item_table WHERE $where_condition";
    
    if (! ($result = $tk->db->sql_query($sql)))
    {
        $error = 'sql';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
        return;
    }
    
    $tk->page->request = 'inner-html';
    $tk->page->process['info'] = false;
    $data = $tk->db->sql_fetchrow($result);
    
    switch ($base_request)
    {
        case 'custom_forms' :
            $data['f_fields'] = unserialize($data['f_fields']);
            if (is_array($data['f_fields']))
            {
                $data['f_fields'] = implode(',', $data['f_fields']);
            }
        
        break;
        default :
        break;
    }

}

/**
 * @method check-
 */

if (preg_match('%^check-.+$%i', $admin_request))
{
    // @todo check
    

    $check_field = preg_replace('%[^\w\._-]+%i', '', $_GET['check']);
    $check_value = preg_replace('%[^\w\._-]+%i', '', $_GET['v']);
    $check_id = (int) $_GET['id'];
    
    if (! in_array($check_field, explode(',', $item_fields)))
    {
        $error = 'unknown_field';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__);
        return;
    }
    
    if ($check_value == '')
    {
        $error = 'empty_value';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__);
        return;
    }
    
    $sql = sprintf("SELECT id FROM $item_table WHERE $check_field = '%s' AND id != '%d'", $check_value, $check_id);
    
    if (! ($result = $tk->db->sql_query($sql)))
    {
        $error = 'sql';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
        return;
    }
    
    if ($tk->db->sql_numrows($result) > 0)
    {
        $error = 'record_exists';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__);
        return;
    }
    
    $tk->eh->message_die($base_request, 'check', '', '', '', 1, '', 'check');
    $data['json'] = json_encode($tk->eh->_result);
}

/**
 * @method listing-
 */

if (preg_match('%^listing-.+$%i', $admin_request))
{
    $tk->page->process['info'] = false;
    
    $aColumns = explode(',', $list_fields);
    
    $sIndexColumn = "id";
    
    if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1')
    {
        $sLimit = "LIMIT " . mysql_real_escape_string($_GET['iDisplayStart']) . ", " . mysql_real_escape_string($_GET['iDisplayLength']);
    }
    
    if (isset($_GET['iSortCol_0']))
    {
        $sOrder = "ORDER BY  ";
        for($i = 0; $i < intval($_GET['iSortingCols']); $i++)
        {
            if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true")
            {
                $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
				 	" . mysql_real_escape_string($_GET['sSortDir_' . $i]) . ", ";
            }
        }
        
        $sOrder = substr_replace($sOrder, "", - 2);
        if ($sOrder == "ORDER BY")
        {
            $sOrder = "";
        }
    }
    
    if ($_GET['sSearch'] != "")
    {
        $sWhere = "WHERE (";
        for($i = 0; $i < count($aColumns); $i++)
        {
            $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR ";
        }
        $sWhere = substr_replace($sWhere, "", - 3);
        $sWhere .= ')';
    }
    
    for($i = 0; $i < count($aColumns); $i++)
    {
        if ($_GET['bSearchable_' . $i] == "true" && isset($_GET['sSearch_' . $i]))
        {
            if ($sWhere == "")
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i] . " LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
        }
    }
    
    $sQuery = "
		SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . ",id,createtime,status
		FROM   $item_table
		$sWhere
		$sOrder
		$sLimit
	";
    $rResult = $tk->db->sql_query($sQuery);
    
    /* Data set length after filtering */
    
    $iFilteredTotal = $tk->db->sql_numrows($rResult);
    
    /* Total data set length */
    $sQuery = "
		SELECT COUNT(" . $sIndexColumn . ")
		FROM   $item_table
	";
    $rResultTotal = $tk->db->sql_query($sQuery);
    $iTotal = $tk->db->sql_numrows($rResultTotal);
    
    /*
	 * Output
	 */
    $output = array(
            "sEcho" => intval($_GET['sEcho']), 
            "iTotalRecords" => $iTotal, 
            "iTotalDisplayRecords" => $iFilteredTotal, 
            "aaData" => array()
    );
    $k = 0;
    while($aRow = $tk->db->sql_fetchrow($rResult))
    {
        $row = array();
        
        for($i = 0; $i < count($aColumns); $i++)
        {
            if ($aColumns[$i] == "page_url")
            {
                /* Special output formatting for 'version' column */
                $row[$aColumns[$i]] = '/' . $aRow[$aColumns[$i]] . '/';
            }
            else if ($aColumns[$i] != ' ')
            {
                /* General output */
                $row[$aColumns[$i]] = $aRow[$aColumns[$i]];
            }
        }
        
        $output['aaData'][$k] = $row;
        
        /**
         * @todo dynamic code
         */
        
        $output['aaData'][$k]['actions'] = '<a href="#" class="edit-input tk-trigger" data-id="' . $aRow['id'] . '" data-action="edit" data-request="' . $base_request . '" title="' . $lang['edit'] . '"></a><a href="#" class="delete-input tk-trigger" data-id="' . $aRow['id'] . '" data-action="delete" data-request="' . $base_request . '" title="' . $lang['delete'] . '"></a>';
        if ($aRow['status'] == 0)
        {
            $output['aaData'][$k]['actions'] .= '<a href="#" class="tk-trigger inactive-input" data-id="' . $aRow['id'] . '" data-action="toggle" data-value="' . $aRow['status'] . '" data-request="' . $base_request . '"></a>';
        }
        else
        {
            $output['aaData'][$k]['actions'] .= '<a href="#" class="tk-trigger active-input" data-id="' . $aRow['id'] . '" data-action="toggle" data-value="' . $aRow['status'] . '" data-request="' . $base_request . '"></a>';
        }
        
        $k++;
    
    }
    
    $data['json'] = json_encode($output);

}

/**
 * @method save-
 */

if (preg_match('%^save-.+$%i', $admin_request))
{
    
    switch ($base_request)
    {
        case 'website_info' :
            
            $logo = preg_replace('%^' . $config['docroot'] . '%i', '', $logo);
            
            $tmp = preg_replace('%(.+)temp/(.+)%i', '$1' . $admin_page . '/$2', $logo);
            
            $tk->f->move_file($tk->eh, $logo, $tmp);
            
            $logo = $tmp;
            
            $tmp = preg_replace('%(.+)/([\w\s\._-]+)%i', '$1/thumb/$2', $logo);
            
            $params = array(
                    'w' => 80, 
                    'h' => 80
            );
            
            $tk->f->generate_thumb($tk->eh, $logo, $tmp, $params);
            
            $logo_portal = preg_replace('%^' . $config['docroot'] . '%i', '', $logo_portal);
            
            $tmp = preg_replace('%(.+)temp/(.+)%i', '$1' . $admin_page . '/$2', $logo_portal);
            
            $tk->f->move_file($tk->eh, $logo_portal, $tmp);
            
            $logo_portal = $tmp;
            
            $tmp = preg_replace('%(.+)/([\w\s\._-]+)%i', '$1/thumb/$2', $logo_portal);
            
            $params = array(
                    'w' => 200, 
                    'h' => 300
            );
            
            $tk->f->generate_thumb($tk->eh, $logo_portal, $tmp, $params);
            
            unset($tmp);
        
        case 'display_settings' :
        
        case 'configure_variables' :
            
            $sql = "SELECT SQL_CACHE $item_override $item_fields from $item_table WHERE $where_condition $order_by";
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $i = 0;
            
            while($row = $tk->db->sql_fetchrow($result))
            {
                $tmp[$i] = $row;
                $i++;
            }
            
            foreach ( $tmp as $fields )
            {
                $i = ${$fields['config_name']};
                
                if ($i == '' && in_array($i, $upload_fields))
                {
                    $i = $fields['config_value'];
                }
                if ($i == '*delete*' && in_array($i, $upload_fields))
                {
                    $i = '';
                }
                
                $sql = sprintf("UPDATE %s SET config_value = '%s' WHERE config_name = '%s' AND config_group = '%s'", $item_table, $i, $fields['config_name'], $config_group);
                
                if (! ($result = $tk->db->sql_query($sql)))
                {
                    $error = 'sql';
                    $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                    return;
                }
            }
        
        break;
        case 'admin_testimonials' :
            
            if (! $id)
            {
                $error = 'no_id';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $sql = sprintf("SELECT SQL_CACHE $item_fields FROM $item_table WHERE id='%s'", $id);
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            if (! ($tk->db->sql_numrows($result)))
            {
                $error = 'no_record';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $row = $tk->db->sql_fetchrow($result);
        
        break;
        case 'form_fields' :
            
            if (! $id)
            {
                $error = 'no_id';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $sql = sprintf("SELECT SQL_CACHE $item_fields FROM $item_table WHERE id='%s'", $id);
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            if (! ($tk->db->sql_numrows($result)))
            {
                $error = 'no_record';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $row = $tk->db->sql_fetchrow($result);
            
            $sql = sprintf("SELECT id FROM %s where %s = '%s' AND id != '%s'", $item_table, 'ff_tag', $ff_tag, $id);
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            if ($tk->db->sql_numrows($result))
            {
                $error = 'record_exists';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
        
        break;
        
        case 'custom_forms' :
            
            if (! $id)
            {
                $error = 'no_id';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $sql = sprintf("SELECT SQL_CACHE $item_fields FROM $item_table WHERE id='%s'", $id);
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            if (! ($tk->db->sql_numrows($result)))
            {
                $error = 'no_record';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $row = $tk->db->sql_fetchrow($result);
            
            $sql = sprintf("SELECT id FROM %s where %s = '%s' AND id != '%s'", $item_table, 'f_tag', $f_tag, $id);
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            if ($tk->db->sql_numrows($result))
            {
                $error = 'record_exists';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $f_fields = str_replace('save-f_fields-', '', $f_fields);
            
            $f_fields = serialize(explode(',', $f_fields));
        
        break;
        
        default :
            $error = 'unknown_command';
            $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
            return;
        break;
    }
    
    $tmparr = explode(",", $item_fields);
    $tmp = array();
    
    foreach ( $tmparr as $v )
    {
        
        if (isset(${$v}))
        {
            $tmp[] = sprintf("%s = '%s'", $v, ${$v});
        }
        else
        {
            $tmp[] = sprintf("%s = '%s'", $v, $row[$v]);
        }
    
    }
    $tmp = implode(",", $tmp);
    
    $sql = sprintf("UPDATE %s set %s WHERE id='%d'", $item_table, $tmp, $id);
    
    unset($tmp);
    unset($tmparr);
    
    if (! ($result = $tk->db->sql_query($sql)))
    {
        $error = 'sql';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $tk->db->sql_error());
        return;
    }
    
    $tk->eh->message_die($base_request, 'save', '', '', '', 1, '', 'success');
    
    $tk->page->_pv['items'] = $item_array;
    
    $data['json'] = json_encode($tk->eh->_result);

}

/**
 * @method toggle-
 */
if (preg_match('%^toggle-.+$%i', $admin_request))
{
    $id = (int) $_GET['id'];
    $toggle = ! (int) $_GET['toggle'];
    
    if (! $id)
    {
        $error = 'no_id';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
        return;
    }
    
    $sql = sprintf("UPDATE %s set status = '%d' where id = '%d'", $item_table, $toggle, $id);
    
    if (! ($result = $tk->db->sql_query($sql)))
    {
        $error = 'sql';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
        return;
    }
    
    $tk->eh->message_die($base_request, 'toggle', '', '', '', 1, '', 'success');
    
    $tk->page->_pv['items'] = $item_array;
    
    $data['json'] = json_encode($tk->eh->_result);

}

/**
 * @method new-
 */

if (preg_match('%^new-.+$%i', $admin_request))
{
    
    switch ($base_request)
    {
        case 'display_settings' :
        case 'rets_settings' :
        
        break;
        
        case 'form_fields' :
            
            $sql = sprintf("SELECT id FROM %s where %s = '%s'", $item_table, 'ff_tag', $ff_tag);
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            if ($tk->db->sql_numrows($result))
            {
                $error = 'record_exists';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $ff_required = (int) $ff_required;
            
            if (! in_array($ff_type, array(
                    'radio', 
                    'checkboxg', 
                    'select'
            )))
            {
                $ff_params = '';
            }
        
        break;
        
        case 'custom_pages' :
            
            $sql = sprintf("SELECT id FROM %s where %s = '%s'", $item_table, 'page_url', $page_url);
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            if ($tk->db->sql_numrows($result))
            {
                $error = 'record_exists';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $page_group = in_array($page_group, array(
                    'sys', 
                    'user'
            )) ? $page_group : 'user';
            
            if (! $page_squeeze)
            {
                $squeeze_page = 0;
                $squeeze_form = 0;
            }
        
        break;
        
        case 'custom_forms' :
            
            $sql = sprintf("SELECT id FROM %s where %s = '%s'", $item_table, 'f_tag', $f_tag);
            
            if (! ($result = $tk->db->sql_query($sql)))
            {
                $error = 'sql';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            if ($tk->db->sql_numrows($result))
            {
                $error = 'record_exists';
                $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
                return;
            }
            
            $f_captcha = (int) $f_captcha;
            $f_notification = (int) $f_notification;
            $f_deletelink = (int) $f_deletelink;
            
            $f_fields = str_replace('new-f_fields-', '', $f_fields);
            
            $f_fields = serialize(explode(',', $f_fields));
        
        break;
        
        case 'admin_testimonials' :
        
        break;
        default :
            return;
        break;
    }
    
    $item_fields = explode(",", $item_fields);
    
    $tmp = array();
    $tmparr = array();
    
    $status = 1;
    $createtime = time();
    
    foreach ( $item_fields as $k => $v )
    {
        if ($v == 'id')
        {
            continue;
        }
        
        if (isset(${$v}))
        {
            $tmp[] = sprintf("'%s'", ${$v});
            $tmparr[] = $v;
        }
    }
    
    $tmp = implode(",", $tmp);
    $item_fields = implode(",", $tmparr);
    
    $sql = sprintf("INSERT INTO %s (%s) VALUES(%s)", $item_table, $item_fields, $tmp);
    
    unset($tmp);
    unset($tmparr);
    
    if (! ($result = $tk->db->sql_query($sql)))
    {
        $error = 'sql';
        $tk->eh->message_die($base_request, $error, __LINE__, __FILE__, $sql);
        return;
    }
    
    $tk->eh->message_die($base_request, 'new', '', '', '', 1, '', 'success');
    
    $tk->page->_pv['items'] = $item_array;
    
    $data['json'] = json_encode($tk->eh->_result);

}

unset($tmp);